﻿
var Artifacts = './RPS.json';
var ContractAddress = "0x3ee71457319887068f78b6489644be134d14115f";
var instance;
var accounts;
var account;

App = {
  	web3Provider: null,
  	contracts: {},

  	init: function() {
    	return App.initWeb3();
  	},

  	initWeb3: function() {
		if (typeof web3 !== 'undefined') {
			alert("metamask");
	  		App.web3Provider = web3.currentProvider;
		} 
		else {
			alert("##### local #####");
			App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
		}
		web3 = new Web3(App.web3Provider);
		
	    // Get the initial account balance so it can be displayed.
	    web3.eth.getAccounts(function(err, accs) {
	      	if (err != null) {
	        	alert("There was an error fetching your accounts.");
	        	return;
	      	}	
	      	if (accs.length == 0) {
	        	alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
	        	return;
	      	}	
	      	accounts = accs;
	      	account = accounts[0];
	      	alert("account:" + account);
	    });		

    	return App.initContract();
  	},

  	initContract: function() {
		$.getJSON(Artifacts, function(data) {
	  		var RpsArtifact = data;
	  		App.contracts.RPS = TruffleContract(RpsArtifact);
	
	  		// Set the provider for our contract
	  		App.contracts.RPS.setProvider(App.web3Provider);
			
			// 
			instance = App.contracts.RPS.at(ContractAddress);
	      	alert("instance ready.");
		});		
  	},

	setStatus: function(message) {
		var status = document.getElementById("status");
	    status.innerHTML = message;
	},
	
	query: function() {
	    var self = this;
	    var game = document.getElementById("game").value;

    	self.setStatus("please wait ...");

		instance.query.call(game).then(function(result) {
	    	console.log(result);
	    	self.setStatus(result);
	    })
	    .catch(function(e) {
	      	console.log(e);
	      	self.setStatus("Error. see log.");
	    });
	}
};

$(function() {
 	$(window).load(function() {
   	 	App.init();
 	});
});
